<?php
namespace app\index\controller;
use think\facade\View;
use think\facade\Db;

class Index
{
    public function index()
    {
        return '请从正确的入口进入！';
    }

    public function test(){

        return View::fetch();
    }

    public function gAi(){
        $text=$_POST['text'];
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "https://api.openai.com/v1/completions");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, '{
          "model": "text-davinci-003",
          "prompt": "'.$text.'",
          "max_tokens": 2048
        }');
        curl_setopt($ch, CURLOPT_POST, 1);

        // Set the API key as an HTTP header
        $headers = array();
        $headers[] = "Content-Type: application/json";
        $headers[] = "Authorization: Bearer 这里输入你获得的API密钥";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Send the request and parse the response
        $response = curl_exec($ch);
        $response_data = json_decode($response, true);
        //var_dump($response_data);

        if (curl_errno($ch)) {
            // If there was an error executing the cURL request, print it out
            echo 'Error: ' . curl_error($ch);
        } else {

            $result = array(
                'code'=> 200,
                'msg'=>"获取成功",
                'data'=>array(
                    'html'=> $response_data['choices'][0]['text'],
                    'title'=>$text
                ),
            );
            $res = array();
            $res = $result['data'];
            /**
             * 这段是将对话内容存入数据库的操作
            $gptdata['content'] = $res['html'];
            $gptdata['title'] = $text;
            $gptdata['addtime'] = time();
            Db::name('gptlog') -> insert($gptdata);
             */
            View::assign('res',json_encode($result['data'],320));
            return View::fetch('list');

        }

        curl_close($ch);

    }

}
